//获取验证码(注册)
function getcode(val) {
  counttime = 60;
  if ($.trim($('#registverify_phone').val()) == "") {
    alert("请先输入电话号码！");
    return;
  }
  if (!isMobil($.trim($('#registverify_phone').val()))) {
    alert("电话号码有误，请检查电话号码格式是否正确！");
    return;
  }
  var data = {
    PhoneNumber: $.trim($('#registverify_phone').val()),
    VerifyCodeType: 1,
    Userid: 0,
  }
  val.setAttribute("disabled", true);
  $.ajax({
    type: "POST",
    url: "http://221.10.2.222:5680/api/ow/Consumers/GetPhoneVerificationCodePc",
    dataType: "json",
    data: data,
    success: function (data) {

      switch (data) {
        case 1:
          settime(val);
          break;
        case -1:
          alert("验证码获取失败");
          val.removeAttribute("disabled");
          break;
        case -2:
          alert("手机号未注册");
          val.removeAttribute("disabled");
          break;
        case -3:
          alert("手机号已被注册");
          val.removeAttribute("disabled");
          break;
        default:
          alert("验证码获取失败");
          val.removeAttribute("disabled");
      }
    }
  });
}

//注册第一步
function registerfirst() {

  if (!isMobil($.trim($('#registverify_phone').val()))) {
    alert("电话号码有误，请检查电话号码格式是否正确！");
    return;
  }
  if ($.trim($('#registverify_phone').val()) == "" || $.trim($('#registverify_code').val()) == "") {
    alert("请将信息填写完整！");
    return;
  }
  if ($("#check_code").prop("checked") == false) {
    alert("必须阅读并同意《用户注册协议》才能注册！");
    return;
  }
  var data = {
    PhoneNumber: $.trim($('#registverify_phone').val()),
    VerifyCode: $.trim($('#registverify_code').val())
  }
  $.ajax({
    type: "POST",
    url: "http://221.10.2.222:5680/api/ow/Consumers/ValidateLoginPc",
    dataType: "json",
    data: data,
    success: function (data) {

      switch (data) {
        case 1:
          $(".step_1").css("display", "none");
          $(".step_2").css("display", "block");
          break;
        case -2:
          alert("验证码错误");
          break;
        case 0:
          alert("验证码过期");
          break;
      }
    }
  });
}

//确定注册
function registersure() {
  if ($.trim($('#register_name').val()) == "" || $.trim($('#register_idcard').val()) == "") {
    alert("请将信息填写完整！");
    return;
  }

  if (idCardNo($.trim($('#register_idcard').val())) == false) {
    alert("身份证号码格式不正确！");
    return;
  }
  if ($.trim($('#register_password').val()).length > 12 || $.trim($('#register_password').val()).length < 8) {
    alert("请设置8-12位密码！");
    return;
  }
  if ($.trim($('#register_password').val()) != $.trim($('#register_quepassword').val())) {
    alert("两次密码不一样！");
    return;
  }
  var data = {
    ConsumersName: $.trim($('#register_name').val()),
    Phone: $.trim($('#registverify_phone').val()),
    Idcard: $.trim($('#register_idcard').val()),
    Password: $.trim($('#register_password').val()),
    IsAgree: 0
  }
  $.ajax({
    type: "POST",
    url: "http://221.10.2.222:5680/api/ow/Consumers/AddPc",
    dataType: "json",
    data: data,
    success: function (data) {

      switch (data) {
        case 0:
          alert("注册成功！");
          window.location.href = "../login/login.html";
          break;
        case -3:
          alert("手机号已注册！");
          break;
        case -4:
          alert("用户名已被使用！");
          break;
        case -6:
          alert("身份证号码已注册！");
          break;
        default:
          alert("注册失败！");
      }
    }
  });
}

///手机号密码登录
function login() {
  jQuery.support.cors = true;
  var name = $('#name').val();
  var pwd = $('#pwd').val();
  //var pwd = $('#pwd').val();
  //alert($.md5(pwd));
  if (!isMobil(name)) {
    alert("电话号码有误，请检查电话号码格式是否正确！");
    return;
  }
  var url = "http://221.10.2.222:5680/api/ow/Consumers/Login/" + $.trim(name) + "/" + pwd;
  if (name == '' || pwd == '') {
    alert('用户名或密码不能为空！');
    return;
  } else {
    $.ajax({
      type: "GET",
      url: url,
      dataType: "json",
      success: function (data) {
        if (data == "手机号还没有注册哟！") {
          alert(data);
        } else if (data == "手机号或密码不正确！") {
          alert(data);
        } else {
          getconsumerinfo(name)
          // setSessionKey(data, name);
        }
      }
    });
  }
}

///手机号验证码登录
function vircodelogin() {
  jQuery.support.cors = true;
  var name = $('#verify_phone').val();
  var pwd = $('#verify_code').val();
  //var pwd = $('#pwd').val();
  //alert($.md5(pwd));
  if (!isMobil(name)) {
    alert("电话号码有误，请检查电话号码格式是否正确！");
    return;
  }
  var url = "http://221.10.2.222:5680/api/ow/Consumers/ValidateLoginPc/" + $.trim(name) + "/" + pwd;
  if (name == '' || pwd == '') {
    alert('用户名或验证码不能为空！');
    return;
  } else {
    $.ajax({
      type: "GET",
      url: url,
      dataType: "json",
      success: function (data) {
        if (data == "手机号还没有注册哟！") {
          alert(data);
        } else if (data == "手机号或验证码不正确！") {
          alert(data);
        } else {
          var Days = 7; //此 cookie 将被保存 30 天
          var exp = new Date(); //new Date("December 31, 9998");
          exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
          document.cookie = "value=" + data.JobNumber + ";expires=" + exp.toGMTString() + ";path=/";
          document.cookie = "id=" + data.Employeeid + ";expires=" + exp.toGMTString() + ";path=/";
          document.cookie = "type=" + data.ConsumerType + ";expires=" + exp.toGMTString() + ";path=/";
          var aa = document.cookie.split(";")[2].split("=")[1];
          window.location.href = "../Home/Index.html";
        }
      },
      error: function (XMLHttpRequest, textStatus, errorThrown) {
        var data = JSON.parse(XMLHttpRequest.responseText);
        alert(data.Message)
        showLoginError(data.Message)
      },
    });
  }
}
///获取验证码(登录)
function getcodeloginaa(val) {
  counttime = 60;
  if ($.trim($('#verify_phone').val()) == "") {
    alert("请先输入电话号码！");
    return;
  }
  if (!isMobil($.trim($('#verify_phone').val()))) {
    alert("电话号码有误，请检查电话号码格式是否正确！");
    return;
  }
  var data = {
    PhoneNumber: $.trim($('#verify_phone').val()),
    VerifyCodeType: 2,
    Userid: 0,
  }
  // val.setAttribute("disabled", true);
  $.ajax({
    type: "POST",
    url: "http://221.10.2.222:5680/api/ow/Consumers/GetPhoneVerificationCodePc",
    dataType: "json",
    data: data,
    success: function (data) {

      switch (data) {
        case 1:
          settime(val);
          break;
        case -1:
          alert("验证码获取失败");
          val.removeAttribute("disabled");
          break;
        case -2:
          alert("手机号未注册");
          val.removeAttribute("disabled");
          break;
        case -3:
          alert("手机号已被注册");
          val.removeAttribute("disabled");
          break;
        default:
          alert("验证码获取失败");
          val.removeAttribute("disabled");
      }
    }
  });
}

///忘记密码第一步手机号和验证码验证
function forgertpwdcodefirst() {
  if ($.trim($('#forgetpwd_phone').val()) == "" || $.trim($('#forgetpwd_getcode').val()) == "") {
    alert("电话号码和验证码不能为空！");
    return;
  }
  var data = {
    PhoneNumber: $.trim($('#forgetpwd_phone').val()),
    VerifyCode: $.trim($('#forgetpwd_getcode').val())
  }
  $.ajax({
    type: "POST",
    url: "http://221.10.2.222:5680/api/ow/Consumers/ValidateLoginPc",
    dataType: "json",
    data: data,
    success: function (data) {

      switch (data) {
        case 1:
          $("#forgetpwd_firstone").hide();
          $("#forgetpwd_firsttwo").show();
          $('#forgetpwd_getcode').val("");
          break;
        case -2:
          alert("验证码错误");
          break;
        case 0:
          alert("验证码过期");
          break;
      }
    }
  });
}
///忘记密码修改验证码

function forgertpwdcode(val) {

  counttime = 60;
  if ($.trim($('#forgetpwd_phone').val()) == "") {
    alert("请先输入电话号码！");
    return;
  }
  if (!isMobil($.trim($('#forgetpwd_phone').val()))) {
    alert("电话号码有误，请检查电话号码格式是否正确！");
    return;
  }
  var data = {
    PhoneNumber: $.trim($('#forgetpwd_phone').val()),
    VerifyCodeType: 2,
    Userid: 0,
  }
  val.setAttribute("disabled", true);
  $.ajax({
    type: "POST",
    url: "http://221.10.2.222:5680/api/ow/Consumers/GetPhoneVerificationCodePc",
    dataType: "json",
    data: data,
    success: function (data) {

      switch (data) {
        case 1:
          settime(val);
          break;
        case -1:
          alert("验证码获取失败");
          val.removeAttribute("disabled");
          break;
        case -2:
          alert("手机号未注册");
          val.removeAttribute("disabled");
          break;
        case -3:
          alert("手机号已被注册");
          val.removeAttribute("disabled");
          break;
        default:
          alert("验证码获取失败");
          val.removeAttribute("disabled");;
      }
    }
  });
}
//修改密码
function forgetpwdTwo() {
  if ($.trim($('#forgetpwdnew').val()) == "") {
    alert("请输入新密码！");
    return;
  }
  if ($('#forgetpwdnew').val() != $('#forgetpwdnewtwo').val()) {
    alert("两次密码不一样！");
    return;
  }
  var newpwd = $.trim($('#forgetpwdnew').val());


  var data = {
    "phone": $.trim($('#forgetpwd_phone').val()),
    "newpassword": newpwd,
  }
  $.ajax({
    type: "POST",
    url: "http://221.10.2.222:5680/api/ow/Consumers/UpdatePasswordForget",
    dataType: "json",
    data: data,

    success: function (data) {
      switch (data) {
        case -1:
          alert("修改失败");
          break;
        case 0:
          alert("修改成功");
          window.location.href = "../login/login.html";
          break;
      }
    }
  });

}

/*手机号码验证*/
function isMobil(s) {
  var patrn = /(^0{0,1}1[3|4|5|6|7|8|9][0-9]{9}$)/;
  if (!patrn.exec(s)) {
    return false;
  }
  return true;
}

///身份证合法性校验
function idCardNo(code) {
  var city = {
    11: "北京",
    12: "天津",
    13: "河北",
    14: "山西",
    15: "内蒙古",
    21: "辽宁",
    22: "吉林",
    23: "黑龙江 ",
    31: "上海",
    32: "江苏",
    33: "浙江",
    34: "安徽",
    35: "福建",
    36: "江西",
    37: "山东",
    41: "河南",
    42: "湖北 ",
    43: "湖南",
    44: "广东",
    45: "广西",
    46: "海南",
    50: "重庆",
    51: "四川",
    52: "贵州",
    53: "云南",
    54: "西藏 ",
    61: "陕西",
    62: "甘肃",
    63: "青海",
    64: "宁夏",
    65: "新疆",
    71: "台湾",
    81: "香港",
    82: "澳门",
    91: "国外 "
  };
  var tip = "";
  var pass = true;

  if (!code || !/^(\d{6})(19|20)(\d{2})(1[0-2]|0[1-9])(0[1-9]|[1-2][0-9]|3[0-1])(\d{3})(\d|X|x)?$/i.test(code)) {
    tip = "身份证号格式错误";
    pass = false;
  } else if (!city[code.substr(0, 2)]) {
    tip = "地址编码错误";
    pass = false;
  } else {
    //18位身份证需要验证最后一位校验位
    if (code.length === 18) {
      code = code.split('');
      //∑(ai×Wi)(mod 11)
      //加权因子
      var factor = [7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2];
      //校验位
      var parity = [1, 0, 'X', 9, 8, 7, 6, 5, 4, 3, 2];
      var sum = 0;
      var ai = 0;
      var wi = 0;
      for (var i = 0; i < 17; i++) {
        ai = code[i];
        wi = factor[i];
        sum += ai * wi;
      }
      var last = parity[sum % 11];
      if (parity[sum % 11] != code[17]) {
        tip = "校验位错误";
        pass = false;
      }
    }
  }
  if (!pass) console.log(tip);
  return pass;
}

// 验证码倒计时
var counttime = 60;
var interval;

function settime(val) {
  if (counttime != 0) {
    window.clearInterval(interval);
    interval = setInterval(function () {
      getsettime(val)
    }, 1000)
  }
}

function getsettime(val) {
  if (counttime == 0) {
    window.clearInterval(interval);
    val.removeAttribute("disabled");
    val.style.color = "red";
    val.style.border = "1px solid red";
    val.value = "获取验证码";

  } else {
    val.setAttribute("disabled", true);
    val.style.color = "#666";
    val.style.border = "1px solid #666";
    val.value = "重新发送(" + counttime + ")";
    counttime = counttime - 1;
  }
}

// 切换登录方式
$('.js_change_login').on('click', function () {
  var idx = $(this).index()
  $(this).addClass('active').siblings().removeClass('active')
  $('.login_phone').siblings().removeClass('active').end().eq(idx).addClass('active')
})

function setSessionKey(data, name) {
  var postData = {
    "userName": name,
    "sessionKey": JSON.stringify(data)
  };
  $.post('http://www.renhexf.com/Login/KeepSessionKey', postData,
    function (reslut) {
      if (reslut) {
        getconsumerinfo(name)
      } else {
        alert("当前用户不存在或密码错误！");
      }
    });
}

function getconsumerinfo(phone) {
  var url = "http://221.10.2.222:5680/api/ow/Consumers/GetEmployeesModelByPhone/" + phone;
  $.ajax({
    type: "GET",
    url: url,
    dataType: "json",
    success: function (data) {
      //根据登录信息得到cookie
      var Days = 7; //此 cookie 将被保存 30 天
      var exp = new Date(); //new Date("December 31, 9998");
      exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
      document.cookie = "value=" + data.consumersname + ";expires=" + exp.toGMTString() + ";path=/";
      document.cookie = "id=" + data.userid + ";expires=" + exp.toGMTString() + ";path=/";
      document.cookie = "type=" + data.consumerstype + ";expires=" + exp.toGMTString() + ";path=/";
      var aa = document.cookie.split(";")[2].split("=")[1];

      top.location.reload();
      //window.location.href = logionhref;
      window.location.href = "../Home/Index.html";
    }
  });
}